package com.concurrent.synchronizeandreentrant;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: MyReentrantLock
 * @Description: 重入锁
 * @author: li
 * @Date: 2021/8/18 4:34 下午
 */
public class MyReentrantLock {
    /**
     * true表示公平锁， false表示非公平锁，默认锁是非公平的。同样synchronized，也是非公平的
     * 公平锁严重影响性能
     */
    final Lock lock = new ReentrantLock(false);
    int sum = 0;

    public MyReentrantLock(int sum) {
        this.sum = sum;
    }

    public MyReentrantLock() {
    }

    public void add(){
        // lock必须紧跟try-finally，并且在finally的第一行释放锁。
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                sum++;
                System.out.println(sum+"\n");
            }
        }finally {
            lock.unlock();  // 确保释放锁，以免发生死锁。
        }

    }

    public static void main(String[] args) {
        int corePoolSize = 4;
        int maximumPoolSize = 10;
        long keepAliveTime = 2;
        TimeUnit timeUnit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(2);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, queue, new ThreadPoolExecutor.AbortPolicy());

        MyReentrantLock myReentrantLock = new MyReentrantLock();
        for (int i = 0; i < 4; i++) {

            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            final int index = (i+1);
                threadPoolExecutor.submit(() -> {

                    System.out.println(index +"线程");
                    myReentrantLock.add();
                });


        }
        threadPoolExecutor.shutdown();

    }

}
